
# 用户管理相关视图
from .role_views import roles_view, add_role_view, edit_role_view
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User, Permission, Group
from django.shortcuts import render, redirect, get_object_or_404
from django.http import HttpRequest, HttpResponse
from LogisticsCard.models import Log
from LogisticsCard.permission_dict import permission_cn
from django.contrib.auth import update_session_auth_hash


@login_required
def users_view(request: HttpRequest) -> HttpResponse:
    """
    用户列表视图，展示当前用户可见的所有用户信息。
    只显示配置用户和管理员，不显示普通用户。
    :param request: HttpRequest对象
    :return: 渲染用户列表页面
    """
    from LogisticsCard.models import UserProfile
    current_user = request.user
    # 只显示配置用户和管理员，过滤掉普通用户
    users = User.objects.filter(
        is_active=True,
        profile__type__in=['admin', 'config_user'],
        profile__delete_at__isnull=True
    ).select_related('profile')
    from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger
    paginator = Paginator(users, 10)
    page = request.GET.get('page')
    try:
        page_obj = paginator.page(page)
    except PageNotAnInteger:
        page_obj = paginator.page(1)
    except EmptyPage:
        page_obj = paginator.page(paginator.num_pages)
    return render(request, 'users/index.html', {'page_obj': page_obj})


@login_required



def add_user_view(request: HttpRequest) -> HttpResponse:
    """
    用户创建视图，处理用户表单提交。
    支持姓名、公司名、手机号、公司地址、邮箱、备注、收件人、电话、收货地址字段，并同步 Address 表。
    """
    from LogisticsCard.models import UserProfile, Address
    if request.method == 'POST':
        username = request.POST.get('username')
        email = request.POST.get('email')
        password = request.POST.get('password')
        user_type = request.POST.get('user_type', 'user')  # 默认为普通用户
        is_active = request.POST.get('is_active') == 'True'
        realname = request.POST.get('realname')
        company_name = request.POST.get('company_name')
        phone = request.POST.get('phone')
        address_field = request.POST.get('address')
        remark = request.POST.get('remark')
        receiver = request.POST.get('receiver')
        delivery_phone = request.POST.get('delivery_phone')
        delivery_address = request.POST.get('delivery_address')
        
        # 根据用户类型设置权限
        if not User.objects.filter(username=username).exists():
            user = User.objects.create_user(username=username, email=email, password=password)
            # 根据用户类型设置相应权限
            if user_type == 'admin':
                user.is_superuser = True
                user.is_staff = True
            elif user_type == 'config_user':
                user.is_superuser = False
                user.is_staff = True  # 配置用户需要能访问后台
            else:  # user
                user.is_superuser = False
                user.is_staff = False
            user.is_active = is_active
            user.save()
            Log.objects.create(user=request.user, action='other', detail=f'添加用户:{user.username}')
            UserProfile.objects.create(
                user=user,
                realname=realname,
                type=user_type,
                operator=request.user,
                delete_at=None
            )
            Address.objects.create(user=user, receiver=receiver, phone=delivery_phone, address=delivery_address, delete_at=None)
            return redirect('/users/')
        else:
            return render(request, 'users/add.html', {'error': '用户名已存在'})
    return render(request, 'users/add.html')

@login_required



def edit_user_view(request: HttpRequest, user_id: int) -> HttpResponse:
    """
    用户编辑视图，支持同步修改姓名、公司名、手机号、公司地址、邮箱、备注、收件人、电话、收货地址。
    """
    from LogisticsCard.models import Address, UserProfile, Customer
    user = User.objects.get(id=user_id)
    customer = Customer.objects.filter(user=user).first()
    address_obj = Address.objects.filter(customer=customer, delete_at__isnull=True).first() if customer else None
    profile = UserProfile.objects.filter(user=user, delete_at__isnull=True).first()
    if request.method == 'POST':
        user.username = request.POST.get('username')
        user.email = request.POST.get('email')
        user_type = request.POST.get('user_type', 'user')
        user.is_active = request.POST.get('is_active') == 'True'
        
        # 根据用户类型设置权限
        if user_type == 'admin':
            user.is_superuser = True
            user.is_staff = True
        elif user_type == 'config_user':
            user.is_superuser = False
            user.is_staff = True
        else:  # user
            user.is_superuser = False
            user.is_staff = False
        user.save()
        
        # 获取其他表单数据
        realname = request.POST.get('realname')
        company_name = request.POST.get('company_name')
        phone = request.POST.get('phone')
        address_field = request.POST.get('address')
        remark = request.POST.get('remark')
        receiver = request.POST.get('receiver')
        delivery_phone = request.POST.get('delivery_phone')
        delivery_address = request.POST.get('delivery_address')
        
        if profile:
            profile.realname = realname
            profile.type = user_type
            profile.save()
        else:
            UserProfile.objects.create(
                user=user,
                realname=realname,
                type=user_type,
                operator=request.user,
                delete_at=None
            )
        
        if address_obj:
            address_obj.receiver = receiver
            address_obj.phone = delivery_phone
            address_obj.address = delivery_address
            address_obj.save()
        elif customer:
            Address.objects.create(customer=customer, receiver=receiver, phone=delivery_phone, address=delivery_address)
        Log.objects.create(user=request.user, action='other', detail=f'编辑用户:{user.username}')
        return redirect('/users/')
    return render(request, 'users/edit.html', {'user': user, 'address': address_obj, 'profile': profile})

@login_required
def delete_user_view(request, user_id):
    from LogisticsCard.models import UserProfile, Address
    from django.utils import timezone
    user = get_object_or_404(User, id=user_id)
    username = user.username
    # 虚拟删除 UserProfile 和 Address
    UserProfile.objects.filter(user=user).update(delete_at=timezone.now())
    Address.objects.filter(user=user).update(delete_at=timezone.now())
    user.is_active = False
    user.save()
    Log.objects.create(user=request.user, action='other', detail=f'虚拟删除用户:{username}')
    return redirect('/users/')

@login_required
def change_password_view(request):
    msg = ''
    error = ''
    if request.method == 'POST':
        old_password = request.POST.get('old_password')
        new_password = request.POST.get('new_password')
        confirm_password = request.POST.get('confirm_password')
        if not request.user.check_password(old_password):
            error = '原密码错误！'
        elif new_password != confirm_password:
            error = '新密码两次输入不一致！'
        elif len(new_password) < 4:
            error = '新密码长度不能少于4位！'
        else:
            request.user.set_password(new_password)
            request.user.save()
            update_session_auth_hash(request, request.user)
            from models import Log
            Log.objects.create(user=request.user, action='other', detail='修改密码')
            msg = '密码修改成功！'
    return render(request, 'change_password.html', {'msg': msg, 'error': error})

